package com.hzy.fivepalace.wx.annotation.support;

import com.hzy.fivepalace.common.consts.CommConsts;
import com.hzy.fivepalace.common.exception.NoLoginException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.hzy.fivepalace.wx.annotation.LoginUser;
import com.hzy.fivepalace.wx.service.UserTokenManager;

import javax.annotation.Resource;

@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Resource
    private UserTokenManager userTokenManager;


    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Integer.class)
                && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container, NativeWebRequest request,
                                  WebDataBinderFactory factory) throws Exception {

        LoginUser loginUser = parameter.getParameterAnnotation(LoginUser.class);//获取注解

        String token = request.getHeader(CommConsts.WX_LOGIN_TOKEN_KEY);
        if (StringUtils.isBlank(token)&&loginUser.login()) {
            throw new NoLoginException("请登录");
        }
        Integer userId = userTokenManager.getUserId(token);
        if ((null == userId || userId < 1)&&loginUser.login()) {//如果注解中login为true才去校验是否登录
            throw new NoLoginException("未登录");
        }

        return userId;
    }
}
